﻿using _2._23._2015_GroceryList.Adapters;
using _2._23._2015_GroceryList.Data;
using _2._23._2015_GroceryList.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Microsoft.AspNet.Identity;

namespace _2._23._2015_GroceryList.Controllers
{
    [Authorize]
    public class apiGroceryController : ApiController
    {
        private IGroceryItemsAdapter _adapter;

        /// <summary>
        /// Default Constructor - instantiate a GroceryItemsDataAdapter for the entire object to use
        /// </summary>
        public apiGroceryController()
        {
            _adapter = new GroceryItemsDataAdapter();
        }

        /// <summary>
        /// Overloaded constructor for dependency injection.  Allow another object to pass in an object that implements
        /// the IGroceryItemsAdapter interface
        /// </summary>
        /// <param name="adapter"></param>
        public apiGroceryController(IGroceryItemsAdapter adapter)
        {
            _adapter = adapter;
        }

        /// <summary>
        /// Route: /api/apiGrocery/
        /// Purpose: Get all grocery items
        /// HTTP Verb: GET
        /// </summary>
        /// <returns></returns>
        public IHttpActionResult Get()
        {
            List<GroceryItemViewModel> models = _adapter.GetGroceryItems();

            return Ok(models);
        }

        /// <summary>
        /// Route: /api/apiGrocery/{id}
        /// Purpose: Set the purchase date for the given grocery item ID
        /// HTTP Verb: PATCH
        /// </summary>
        /// <returns></returns>
        public IHttpActionResult Patch(int id)
        {
            DateTime? datePurchased = _adapter.PurchaseGroceryItem(id);

            return Ok(datePurchased);
        }

        /// <summary>
        /// Route: /api/apiGrocery/
        /// Purpose: Add a new grocery item
        /// HTTP Verb: POST
        /// </summary>
        /// <returns></returns>
        public IHttpActionResult Post(GroceryItemViewModel model)
        {
            string userId = User.Identity.GetUserId();

            model.GroceryItemId = _adapter.AddItem(model, userId);

            return Ok(model);
        }
    }
}
